package com.wuwei.jy.Service;

import com.wuwei.jy.utils.AuthorUtil;
import com.wuwei.jy.utils.DateDistance;
import com.wuwei.jy.utils.SignItem;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by Administrator on 2017/6/7.
 */
@Service
public class AuthService {

    /**
     * 通过签名获取用户id
     *
     * @param sign

     * @return
     */
    public String GetUidBySign(String sign) {


        SignItem si = AuthorUtil.getSignData(sign);
        if (si != null) {
            long day = DateDistance.getDistanceDays(new Date(), si.getCreateDate());
            if (day > 2) {
                return null;

            } else {
                return si.getUid();

            }

        }
        return null;

    }

    /**
     * 检查用户是否登陆
     * @param request
     * @return
     */
    public  boolean Auth(HttpServletRequest request) {

        Object o = request.getSession().getAttribute("uid");
        if (o != null) {
            return true;


        } else {
            Cookie[] cookies = request.getCookies();//这样便可以获取一个cookie数组
            for (Cookie cookie : cookies) {
                if (cookie.getName() == "sign") {
                    String sign = cookie.getValue();
                    String id = GetUidBySign(sign);
                    if (!StringUtils.isNoneEmpty(id)) {
                        return true;

                    }
                }
            }

            return false;
        }
    }


    /**
     * 获取登陆用户id
     * @param request
     * @return
     */
    public String LoginUid(HttpServletRequest request) {
        Object o = request.getSession().getAttribute("uid");
        if (o != null) {
            return o.toString();


        } else {
            Cookie[] cookies = request.getCookies();//这样便可以获取一个cookie数组
            for (Cookie cookie : cookies) {
                if (cookie.getName() == "sign") {
                    String sign = cookie.getValue();
                    String id = GetUidBySign(sign);
                    return id;
                }
            }

            return null;

        }
    }
}